<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="主叫号码" prop="callere164">
        <el-input
          v-model="queryParams.callere164"
          placeholder="请输入主叫号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="被叫号码" prop="calleee164">
        <el-input
          v-model="queryParams.calleee164"
          placeholder="请输入被叫号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="原始被叫" prop="calleeaccesse164">
        <el-input
          v-model="queryParams.calleeaccesse164"
          placeholder="请输入原始被叫"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="主叫IP" prop="callerip">
        <el-input
          v-model="queryParams.callerip"
          placeholder="请输入主叫IP"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="对接网关" prop="callergatewayid">
        <el-input
          v-model="queryParams.callergatewayid"
          placeholder="请输入对接网关"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="被叫IP" prop="calleeip">
        <el-input
          v-model="queryParams.calleeip"
          placeholder="请输入被叫IP"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="呼出被叫号码" prop="calleetogatewaye164">
        <el-input
          v-model="queryParams.calleetogatewaye164"
          placeholder="请输入呼出被叫号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="起始时间" prop="starttime">
        <el-date-picker
          v-model="queryParams.starttime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="终止时间" prop="stoptime">
        <el-date-picker
          v-model="queryParams.stoptime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="通话时长" prop="holdtime">
        <el-input
          v-model="queryParams.holdtime"
          placeholder="请输入通话时长"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="挂断方" prop="enddirection">
        <el-select
          v-model="queryParams.enddirection"
          placeholder="请选择挂断方"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ENDDIRECTION)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务标签" prop="phoneTag">
        <el-select
          v-model="queryParams.phoneTag"
          placeholder="请选择业务标签"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PHONE_TAG)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['vos:E-cdr:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="主叫号码" align="center" prop="callere164" />
      <el-table-column label="被叫号码" align="center" prop="calleee164" />
      <el-table-column label="原始被叫" align="center" prop="calleeaccesse164" />
      <el-table-column label="主叫IP" align="center" prop="callerip" />
      <el-table-column label="对接网关" align="center" prop="callergatewayid" />
      <el-table-column label="被叫IP" align="center" prop="calleeip" />
      <el-table-column label="呼出被叫号码" align="center" prop="calleetogatewaye164" />
      <!-- 起始时间（前端按菲律宾时区格式化） -->
      <el-table-column label="起始时间" align="center" prop="starttime">
        <template #default="{ row }">
          {{ formatTs(row.starttime) }}
        </template>
      </el-table-column>
      <!-- 终止时间（前端按菲律宾时区格式化） -->
      <el-table-column label="终止时间" align="center" prop="stoptime">
        <template #default="{ row }">
          {{ formatTs(row.stoptime) }}
        </template>
      </el-table-column>
      <el-table-column label="通话时长" align="center" prop="holdtime" />
      <el-table-column label="话单的唯一标识" align="center" prop="flowno" />
      <el-table-column label="挂断方" align="center" prop="enddirection">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ENDDIRECTION" :value="scope.row.enddirection" />
        </template>
      </el-table-column>
      <el-table-column label="业务标签" align="center" prop="phoneTag">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PHONE_TAG" :value="scope.row.phoneTag" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ECdrForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import download from '@/utils/download'
import { ECdrApi, ECdr } from '@/api/vos/ecdr'
import ECdrForm from './ECdrForm.vue'

/** CDR 列表 */
defineOptions({ name: 'ECdr' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ECdr[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  callere164: undefined,
  calleee164: undefined,
  calleeaccesse164: undefined,
  callerip: undefined,
  callergatewayid: undefined,
  calleeip: undefined,
  calleetogatewaye164: undefined,
  starttime: [],
  stoptime: [],
  holdtime: undefined,
  enddirection: undefined,
  phoneTag: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 菲律宾时区格式化时间戳（毫秒或秒都兼容） */
const formatTs = (v: unknown): string => {
  if (v === null || v === undefined || v === '') return '-'
  let n = typeof v === 'string' ? Number(v) : (v as number)
  if (!Number.isFinite(n)) return String(v)
  // 兼容秒级时间戳
  if (n < 1e12) n = n * 1000

  const parts = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
    timeZone: 'Asia/Manila'
  }).formatToParts(new Date(n))

  const get = (t: string) => (parts.find(p => p.type === t)?.value) || '00'
  return `${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}:${get('second')}`
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ECdrApi.getECdrPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await ECdrApi.deleteECdr(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    await getList()
  } catch {}
}

/** 批量删除CDR */
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await ECdrApi.deleteECdrList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: ECdr[]) => {
  checkedIds.value = records.map((item) => (item as any).id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await ECdrApi.exportECdr(queryParams)
    download.excel(data, 'CDR.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
